using System.IO;

namespace RollManager.Library.Utils
{
    public partial class DirectoryHelper
    {
        public void Delete( string destDir )
        {
            Delete( destDir, FILTER_ALL_FILES, true );
        }

        public void Delete( string destDir, bool recursive )
        {
            Delete( destDir, FILTER_ALL_FILES, recursive );
        }

        public void Delete( string destDir, string filter )
        {
            Delete( destDir, filter, true );
        }

        public void Delete( string destDir, string filter, bool recursive )
        {
            DirectoryInfo targetPath = new DirectoryInfo( destDir );

            if( string.IsNullOrEmpty( filter ) )
            {
                filter = FILTER_ALL_FILES;
            }

            DeleteDirectory( targetPath, filter, recursive );
        }

        private void DeleteDirectory( DirectoryInfo targetPath, string filter, bool recursive )
        {
            // If the target folder does not exist then create it.
            if( !targetPath.Exists )
            {
                return;
            }

            // Delete files first
            foreach( FileInfo fileInfo in targetPath.GetFiles( filter ) )
            {
                LogFormat( "Deleting file {0}", fileInfo.FullName );

                // remove readonly permissions if they are present.
                if( fileInfo.Exists && fileInfo.IsReadOnly )
                {
                    fileInfo.Attributes = FileAttributes.Normal;
                }

                MethodRepeater.RepeatMethod( delegate { fileInfo.Delete(); }, output, 5 );
            }

            if( recursive )
            {
                // Delete sub-folder 
                foreach( DirectoryInfo dirInfo in targetPath.GetDirectories() )
                {
                    DeleteDirectory( dirInfo, filter, recursive );
                }
            }

            // delete the directory if it is empty
            if( targetPath.GetFiles().Length == 0 && targetPath.GetDirectories().Length == 0 )
            {
                MethodRepeater.RepeatMethod( delegate { targetPath.Delete(); }, output, 5 );
            }
        }
    }
}